//
//  XLTabBar.swift
//  WeiboTT
//
//  Created by 王嘉涛 on 2016/11/12.
//  Copyright © 2016年 王嘉涛. All rights reserved.
//

import UIKit

class XLTabBar: UITabBar {

    // 声明一个闭包属性
    var buttonClosure : (() -> ())?
    
    // 添加按钮
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(XLButton)
        
        // 加号按钮监听点击事件
        XLButton.addTarget(self, action:  #selector(clickXLButton), for: .touchUpInside)
        
    }
    @objc private func clickXLButton(){
        
        buttonClosure?()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 重新布置位置
        let w = self.bounds.width / 5
        let h = self.bounds.height
        var index = 0
        
        for Subview in subviews {
         
            if Subview.isKind(of: NSClassFromString("UITabBarButton")!) {
                Subview.frame = CGRect(x: w * (CGFloat)(index), y: 0, width: w, height: h)
                
                index += (index == 1 ? 2 : 1)

            }
        }

        // 设置中间button的位置
        XLButton.bounds.size = CGSize(width: w, height: h)
        XLButton.center = CGPoint(x: self.center.x, y: h * 0.5)
        
    }
    
    // 懒加载button
    lazy var XLButton : UIButton = {
        let but = UIButton()
        but.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        but.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        but.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        but.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        return but
    }()
    
}

